﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using smartcrm.Utilities;
using smartcrm.Models;

namespace smartcrm.Controllers
{
    [Authorization]
    public class MySpaceController : BaseController
    {
        public ActionResult Index()
        {
            MyOrders myOrders = new MyOrders();
            myOrders.InProcessingOrders = GetInProcessingOrderList();
            myOrders.InvolvedgOrders = GetInvolvedOrderList();
            myOrders.FileSizeLimitation = Math.Round(AttachmentConfigurate.SizeLimitation, 2).ToString() + " MB";

            return View(myOrders);
        }

        private List<OrderInfo> GetInProcessingOrderList()
        {
            List<OrderInfo> result;
            string userId = GetLoginUser().UserId;
            IQueryable<OrderInfo> query = (from o in Context.Order.Where(m => m.IsActive && m.CompanyNo == CompanyNo && m.Approved && m.OrderFlow.Where(n => n.IsFinished == false && n.UserId == userId).Count() > 0)
                                           select new OrderInfo
                                           {
                                               OrderNo = o.OrderNo,
                                               CreatedTime = o.CreatedTime,
                                               CustomerShortName = o.Customer.CustomerShortName,
                                               OrderName = o.OrderName,
                                               Contact = o.Contact,
                                               PaymentStatus = o.PaymentStatus,
                                               TransactionDate = o.TransactionDate,
                                               CustomerNo = o.CustomerNo,
                                               FactoryPrice = o.FactoryPrice,
                                               FactoryAmount = o.FactoryAmount,
                                               DetailText = o.DetailText,
                                               Category = o.Category,
                                               CategoryName = o.CategoryName,
                                               Number = o.Number,
                                               FactoryNo = o.FactoryNo,
                                               OrderStatusNo = o.OrderStatusNo,
                                               StatusDescription = o.OrderStatus.StatusName
                                           });


            result = query.ToList();
            foreach (OrderInfo i in result)
            {
                i.PaymentStatusDescription = GetOrderPaymentStatusString(i.PaymentStatus);
            }

            return result;
        }

        private List<OrderInfo> GetInvolvedOrderList()
        {
            List<OrderInfo> result;
            string userId = GetLoginUser().UserId;
            IQueryable<OrderInfo> query = (from o in Context.Order.Where(m => m.IsActive && m.Approved && m.CompanyNo == CompanyNo && m.OrderFlow.Where(n => n.UserId == userId).Count() > 0)
                                           select new OrderInfo
                                           {
                                               OrderNo = o.OrderNo,
                                               CreatedTime = o.CreatedTime,
                                               CustomerShortName = o.Customer.CustomerShortName,
                                               OrderName = o.OrderName,
                                               Contact = o.Contact,
                                               PaymentStatus = o.PaymentStatus,
                                               TransactionDate = o.TransactionDate,
                                               CustomerNo = o.CustomerNo,
                                               FactoryPrice = o.FactoryPrice,
                                               FactoryAmount = o.FactoryAmount,
                                               DetailText = o.DetailText,
                                               Category = o.Category,
                                               CategoryName = o.CategoryName,
                                               Number = o.Number,
                                               FactoryNo = o.FactoryNo,
                                               OrderStatusNo = o.OrderStatusNo,
                                               StatusDescription = o.OrderStatus.StatusName
                                           });


            result = query.ToList();
            foreach (OrderInfo i in result)
            {
                i.PaymentStatusDescription = GetOrderPaymentStatusString(i.PaymentStatus);
            }

            return result;
        }

        public JsonResult GetDetail(string OrderNo)
        {
            JsonResult result = new JsonResult();
            string errorMessage = string.Empty;

            OrderInfo detail = new OrderInfo();
            Order order = Context.Order.FirstOrDefault(m => m.OrderNo == OrderNo);
            if (order == null)
            {
                result.Data = new { code = 1, message = MSG_NoEntityFound };
            }
            else
            {
                detail.OrderNo = order.OrderNo;
                detail.OrderName = order.OrderName;
                detail.CustomerShortName = Context.Customer.First(m => m.CustomerNo == order.CustomerNo).CustomerShortName;
                detail.Contact = order.Contact;
                detail.Creator = order.Creator;
                detail.Memo = order.Memo;
                detail.TransactionDateString = order.TransactionDate.ToString("yyyy-MM-dd");
                detail.CreatedTimeString = order.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss");
                detail.CategoryName = order.CategoryName;
                detail.DetailText = order.DetailText;
                detail.OrderStatusNo = order.OrderStatusNo;
                detail.PaymentStatus = order.PaymentStatus;
                detail.Number = order.Number;
                detail.ExpectDeliveryDateString = order.ExpectDeliveryDate.HasValue ? order.ExpectDeliveryDate.Value.ToString("yyyy-MM-dd") : "";
                detail.StatusDescription = order.OrderStatus.StatusName;
                detail.PaymentStatusDescription = GetOrderPaymentStatusString(detail.PaymentStatus);
                detail.QueryURL = ORDER_QUERY_URL + order.OrderNo + order.QueryCode;

                if (order.PaymentStatus == ((int)OrderPaymentStatus.Unpaid).ToString() ||
                    order.PaymentStatus == ((int)OrderPaymentStatus.PartPaid).ToString())
                {
                    detail.Css = "OrderStatusUnPaid";
                }
                else
                {
                    detail.Css = "OrderStatusPaid";
                }

                detail.Detail += string.Format("{0}({1})", order.CategoryName, order.DetailText);

                List<OrderLog> logs = order.OrderLog.Where(m => m.IsPublic).ToList();

                detail.History = string.Empty;
                foreach (OrderLog h in logs)
                {
                    detail.History += string.Format("{0} {1} {2}", h.LogDate.ToString("yyyy-MM-dd HH:mm:ss"), h.UserName, h.Operation);
                    detail.History += "<br/>";
                }

                detail.steps = new List<JSOrderWorkFlow>();
                List<OrderFlow> orderFlows = Context.OrderFlow.Where(m => m.OrderNo == OrderNo).OrderBy(m => m.OrderFlowNo).ToList();
                foreach (OrderFlow of in orderFlows)
                {
                    JSOrderWorkFlow wf = new JSOrderWorkFlow();
                    wf.StepName = of.WorkFlowStep.WorkFlowStepName;
                    wf.UserName = of.User == null ? "" : of.User.UserName;
                    wf.DateTime = of.EndDate.HasValue ? of.EndDate.Value.ToString("yyyy-MM-dd") : "";
                    wf.IsFinished = of.IsFinished;
                    detail.steps.Add(wf);
                }

                List<OrderAttachment> attachments = Context.OrderAttachment.Where(m => m.OrderNo == OrderNo).ToList();
                detail.Attachments = new List<SimpleItemList>();
                foreach (OrderAttachment o in attachments)
                {
                    detail.Attachments.Add(new SimpleItemList() { ItemText = o.FileName, ItemValue = o.AttachmentNo, Addition1 = o.FileTypeImage, Addition2 = string.Format("{0} {1}", o.Creator, o.Createtime.ToString("yyyy-MM-dd")) });
                }

                detail.OrderMemos = new List<SimpleItemList>();
                foreach (OrderMemo o in order.OrderMemo)
                {
                    detail.OrderMemos.Add(new SimpleItemList() { Addition1 = o.Memo, Addition2 = o.Creator, Addition3 = o.Createtime.ToString("yyyy-MM-dd") });
                }

                result.Data = new { code = 0 ,data=detail};
            }

            return result;
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        public JsonResult UpdatePassword(string OldPassword, string newPassword1, string newPassword2)
        {
            JsonResult result = new JsonResult();
            string userId = GetLoginUser().UserId;
            User user = Context.User.FirstOrDefault(m => m.UserId == userId);
            if (user == null)
            {
                result.Data = new { code = 1, message = MSG_NoEntityFound };
            }
            else if (IS_DEMO)
            {
                result.Data = new { code = 1, message = MSG_IsDemo };
            }
            else if (user.Password != MD5Utility.MD5Encrypt(OldPassword))
            {
                result.Data = new { code = 1, message = "旧密码不对" };
            }
            else
            {
                user.Password = MD5Utility.MD5Encrypt(newPassword1);

                Context.SaveChanges();
                result.Data = new { code = 0 };
            }

            return result;
        }
    }
}
